<template>
  <a-modal
    :title="title"
    :width="1600"
    :height="1000"
    :visible="visible"
    :bodyStyle="bodyStyle"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
    wrapClassName="ant-modal-cust-warp"
    style="top:5%;height: 70%;overflow-y: hidden"
  >
    <template slot="footer">
      <a-button key="back" v-if="isReadOnly" @click="handleCancel">
        关闭
      </a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <div style="width:1000px;margin:30px auto;">
        <a-steps :current="currents" direction="horizontal" size="small" @change="onChange">
          <a-step v-for="(item, index) in stageList" :key="index" :title="item.name" @click="backNow(index)"> </a-step>
        </a-steps>
      </div>
      <a-form
        :form="form"
        id="customerModal"
        v-show="this.model.stageA !== 0 && this.model.stageA !== 8 && this.model.stageA == this.currents"
      >
        <a-col :span="12">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="合同审批流程Id">
            <a-input disabled v-decorator.trim="['approvalId']" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="审批级别">
            <a-input disabled v-decorator.trim="['approvalStage']" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="评审部门">
            <a-input disabled v-decorator.trim="['department']" />
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="this.model.stageA == 4">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否需要采购">
            <!-- <a-input placeholder="请选择付款方式" v-decorator.trim="['payment']" /> -->
            <a-select
              v-decorator.trim="['needPurchase']"
              allowClear
              placeholder="请选择"
              showSearch
              optionFilterProp="children"
            >
              <a-select-option v-for="(item, index) in isNeed" :key="index" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="图片上传">
            <!-- <a-input placeholder="请输入开票金额" v-decorator.trim="['imgUrl']" /> -->
            <div :key="Math.random()">
              <a-upload
                name="file"
                accept="image/png,image/jpeg,image/webp,image/jpg"
                :beforeUpload="beforeUpload"
                :showUploadList="false"
                :multiple="false"
                :headers="tokenHeader"
                :action="importExcelUrl"
                @change="myhandleImportExcel"
              >
                <a-button><a-icon type="upload" />上传</a-button>
              </a-upload>
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="this.model.stageA == 7">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="审批状态">
            <a-select
              v-decorator.trim="['status']"
              allowClear
              placeholder="请选择"
              showSearch
              optionFilterProp="children"
            >
              <a-select-option v-for="(item, index) in status" :key="index" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="审批意见">
            <a-textarea allow-clear placeholder="请输入评审意见" v-decorator.trim="['content']" />
          </a-form-item>
        </a-col>
      </a-form>
      <div v-show="this.model.stageA == 8 || this.model.stageA == 0">
        <a-result
          v-if="this.model.stageA == 8"
          status="success"
          title="审批完成!"
          sub-title="点击步骤条可查看其他部门审批信息"
        >
        </a-result>
        <a-result v-show="this.model.stageA == 0" title="请审批!" sub-title="点击步骤条中销售部开始"
          ><template #icon>
            <a-icon type="smile" theme="twoTone" />
          </template>
        </a-result>
      </div>
      <div
        class="showMessage"
        v-if="this.model.stageA !== 0 && this.model.stageA !== 8 && this.model.stageA !== this.currents"
      >
        <p><span>合同审批流程ID：</span>{{ showMessage.approvalId }}</p>
        <p><span>审批级别：</span>{{ showMessage.approvalStage }}</p>
        <p v-if="this.model.stageA == 4">
          <span>是否需要采购：</span>{{ showMessage.needPurchase == 0 ? '不需要' : '需要' }}
        </p>
        <p><span>评审部门：</span>{{ showMessage.department }}</p>
        <p v-if="this.model.stageA == 7"><span>评审状态：</span>{{ showMessage.status }}</p>
        <p><span>审批意见：</span>{{ showMessage.content }}</p>
        <p><span>图片：</span><img :src="showMessage.imgUrl" alt="" /></p>
      </div>
    </a-spin>
  </a-modal>
</template>
<script>
import pick from 'lodash.pick'
import { auditApproval, checkSupplier } from '@/api/api'
import { getAction, getActionImg } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { autoJumpNextInput } from '@/utils/util'
export default {
  name: 'ActionApprovalModel',
  mixins: [JeecgListMixin],
  components: {},
  data() {
    return {
      title: '操作',
      visible: false,
      model: {},
      isReadOnly: true,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      defaultFileList: null,
      currents: 0,
      showMessage: '',
      bodyStyle: {
        padding: '20',
        'overflow-y': 'auto'
      },
      disableSubmit: false,
      status: [
        {
          id: 0,
          name: '待审批'
        },
        {
          id: 1,
          name: '通过'
        },
        {
          id: 2,
          name: '驳回'
        }
      ],
      isNeed: [
        {
          id: 0,
          name: '不需要'
        },
        {
          id: 1,
          name: '需要'
        }
      ],
      stageList: [
        { id: 0, name: '待审批' },
        { id: 1, name: '销售部' },
        { id: 2, name: '技术部' },
        { id: 3, name: '质检部' },
        { id: 4, name: '生产部' },
        { id: 5, name: '采购部' },
        { id: 6, name: '评审结论' },
        { id: 7, name: '审批意见' },
        { id: 8, name: '审批完成' }
      ],
      dataSource: [],
      confirmLoading: false,
      form: this.$form.createForm(this),
      url: {
        lists: '/contractApproval/getById',
        delete: '/contractProductDelivery/remove',
        importExcelUrl: '/systemConfig/upload' + '?' + `biz=sp`
      }
    }
  },
  created() {},
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}${this.url.importExcelUrl}`
      // return `api${this.url.importExcelUrl}`
    }
  },
  methods: {
    //图片上传前做限制
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        let isType =
          file.type === 'image/jpg' ||
          file.type === 'image/jpeg' ||
          file.type === 'image/png' ||
          file.type === 'image/webp'
        if (!isType) {
          this.$message.error('格式错误,只能上传jpg、jpeg、png、webp')
          return reject(false)
        }
        return resolve(true)
      })
    },
    //步骤条
    onChange(e) {
      //为0为待审批则只能进入销售部填写
      if (this.model.stageA == 0 && this.currents == 0) {
        this.currents = 1
      }
      //不允许查看超过当前进程的信息
      if (this.model.stageA > this.currents) {
        this.$message.warning('暂无数据')
        return
      } else {
        this.getDataFlow(e)
        this.model.stageA = e
      }
    },
    backNow(index) {
      console.log('当前index', index)
      //   console.log('当前stageA', this.model.stageA)
      console.log('currents', this.currents)
      console.log(this.currents == index)
      if (this.currents == index) {
        this.model.stageA = this.currents
        this.currents = index
      }
      //不允许查看超过当前进程的信息
      if (this.model.stageA > this.currents) {
        return
      }
    },
    //获取各部门流程数据
    getDataFlow(e) {
      let params = {
        approvalStage: this.$router.currentRoute.name == '一级审批' ? '1' : '2',
        approvalId: this.model.approvalId ? this.model.approvalId : this.model.id,
        department: e
      }
      getAction('/contractApprovalData/listByCriteria', params).then(res => {
        if (res.code == 10000) {
          this.showMessage = res.data[0]
          this.stageList.map(item => {
            if (this.showMessage.department == item.id) {
              this.showMessage.department = item.name
            }
          })
          this.stageList.map(item => {
            if (this.showMessage.status == item.id) {
              this.showMessage.status = item.name
            }
          })
        } else {
          this.$message.warning(res.message)
          this.showMessage = []
        }
        this.getImg()
        console.log(this.showMessage.department)
      })
    },
    getImg() {
      if (this.showMessage.imgUrl) {
        let params = this.showMessage.imgUrl
        getActionImg('systemConfig/static/' + params).then(res => {
          const captchaImg = window.URL.createObjectURL(res)
          this.showMessage.imgUrl = captchaImg
          console.log(this.showMessage)
        })
      }
    },
    //限制
    disableSubmits() {
      //仅查看时,其他页面为disable
      if (this.model.stageA !== this.currents) {
        this.disableSubmit = true
      } else {
        this.disableSubmit = false
      }
    },
    /* 导入 */
    myhandleImportExcel(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (info.file.response) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 200 || info.file.response.code === 10000) {
            this.$message.success(`${info.file.name} 文件上传成功` || info.file.response.data)
            this.defaultFileList = info.file.response.data
          } else {
            this.$message.warning(info.file.response.message)
          }
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.data}.`)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`文件上传失败: ${info.file.msg} `)
      }
    },
    edit(record) {
      this.currents = record.stageA
      this.visible = true
      this.form.resetFields()
      this.model = Object.assign({}, record)
      //为0为待审批则只能进入销售部填写
      if (this.model.stageA == 0) {
        this.model.department = 1
        record.stageA = 1
      }
      this.defaultFileList = this.model.contractFile
      console.log(this.model)
      this.$nextTick(() => {
        //编辑
        if (record) {
          this.form.setFieldsValue({ approvalId: record.id })
          if (this.$router.currentRoute.name == '一级审批') {
            this.form.setFieldsValue({ approvalStage: 1 })
            this.stageList.map(item => {
              if (item.id == record.stageA || item.id == record.department) {
                this.form.setFieldsValue({ department: item.name })
              }
            })
          } else {
            this.form.setFieldsValue({ approvalStage: 2 })
            this.stageList.map(item => {
              if (item.id == record.stageB) {
                this.form.setFieldsValue({ department: item.name })
              }
            })
          }
        }
        this.form.setFieldsValue(pick(this.model, 'content'))
        //不为待审批和审批完成状态
        if (this.model.stageA !== 0 && this.model.stageA !== 8) {
          autoJumpNextInput('customerModal')
        }
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let formData = Object.assign(values)
          if (this.model.beginNeedGet && this.model.beginNeedPay) {
            that.$message.warn('期初应收和期初应付不能同时输入')
            that.confirmLoading = false
            return
          }
          this.stageList.map(item => {
            if (item.name == formData.department) {
              formData.department = item.id
            }
          })
          formData.imgUrl = this.defaultFileList
          let obj
          if (!this.model.id) {
            obj = auditApproval(formData)
          } else {
            obj = auditApproval(formData)
          }
          obj
            .then(res => {
              if (res.code === 200 || res.code === 10000) {
                this.$message.success('保存成功')
                that.$emit('ok')
              } else {
                // this.$message.warning(res.data.message)
                console.log('404', res)
                this.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              that.close()
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    validateSupplierName(rule, value, callback) {
      let params = {
        name: value,
        type: '客户',
        id: this.model.id ? this.model.id : 0
      }
      checkSupplier(params).then(res => {
        if (res && res.code === 200) {
          if (!res.data.status) {
            callback()
          } else {
            callback('名称已经存在')
          }
        } else {
          callback(res.data)
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.showMessage {
  width: 800px;
  margin: 20px auto;
  padding: 10px;
  border: 1px solid whitesmoke;
  flex-direction: column;
  background-color: whitesmoke;
  p {
    font-size: 14px;
    span {
      font-size: 16px;
      font-weight: 500;
    }
  }
  img {
    width: 100%;
  }
}
</style>
